package eureka.consumer.redissonlock.review.conf;

import cn.hutool.core.util.StrUtil;
import eureka.consumer.redissonlock.BaseRedisProperty;
import lombok.extern.slf4j.Slf4j;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.redisson.config.SingleServerConfig;
import org.redisson.config.TransportMode;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;

/**
 * @Author RenPu
 * @Date 2023/10/7 17:29
 * @Version 1.0
 * @Description:
 **/

@Slf4j
@Configuration
@ConditionalOnClass(RedisTemplate.class)
@EnableConfigurationProperties(BaseRedisProperty.class)
public class RedissonConf {

    @Bean("single")
    public DistributeLockFactoryBean getDistributeLockFactoryBean(BaseRedisProperty baseRedisProperty){
        return new DistributeLockFactoryBean(baseRedisProperty);
    }


    @Bean
    public RedissonClient getRedissonClient(BaseRedisProperty baseRedisProperty){
        log.info("init redisson: {}", baseRedisProperty.toString());
        String mode = baseRedisProperty.getRedisson().getMode();

        //1：获取ip+port
        Integer port = baseRedisProperty.getPort();
        String host = baseRedisProperty.getHost();

        BaseRedisProperty.Redisson redisson=baseRedisProperty.getRedisson();

        //2:创建Redisson配置类，设置网络通信模型例如：NIO,EPLLO等，超时参数

        Config config = new Config();
        if (TransportMode.EPOLL.name().equalsIgnoreCase(redisson.getTransportMode())) {
            config.setTransportMode(TransportMode.EPOLL);
        }
        SingleServerConfig useSingleServer = config.useSingleServer();
        useSingleServer.setAddress("redis://"+host+":"+port);
        useSingleServer.setTimeout(redisson.getTimeOut());
        useSingleServer.setConnectionPoolSize(redisson.getPoolSize());
        //3:根据配置得参数密码，进行设置
        if(StrUtil.isNotBlank(baseRedisProperty.getPassword())){
            log.info("redisson 密码不为空，设置密码");
            useSingleServer.setPassword(baseRedisProperty.getPassword());
        }

        //4：设置链接超时时间
        useSingleServer.setPingConnectionInterval(1000);
        useSingleServer.setConnectionMinimumIdleSize(redisson.getMinIdleSize());

        RedissonClient redissonClient = Redisson.create(config);

        return redissonClient;

    }





}
